package com.one.rope.mvp.basecore.util;

import java.util.Random;

/**
 * 数据表主键生成规则,根据twitter算法演变而来,增加了6位用于生成随机数
 */
public class TableIdUtils {

  private static final int DEFAULT_SERVER_ID = -1;
  private static int server_id = DEFAULT_SERVER_ID;
  private static DigitIdGenerator mainIdGenerator = null;
  private static DigitIdGenerator otherIdGenerator = null;
  private static Object lockObj = new Object();

  static {
    calculateServerId();
  }

  public static int calculateServerId() {
    if (server_id == DEFAULT_SERVER_ID) {
      synchronized (DigitIdGenerator.class) {
        if (server_id == DEFAULT_SERVER_ID) {
          try {
            String serverIdStr = System.getProperty("server.id");
            server_id = new Integer(serverIdStr);
          } catch (Exception e) {
            server_id = new Random().nextInt(1024);
          } finally {
          }
        }
      }
    }
    return server_id;
  }

  private static DigitIdGenerator getMainIdGenerator() {
    if (mainIdGenerator == null) {
      synchronized (TableIdUtils.class) {
        if (mainIdGenerator == null) {
          mainIdGenerator = new DigitIdGenerator(server_id);
        }
      }
    }
    return mainIdGenerator;
  }

  private static DigitIdGenerator getOtherIdGenerator() {
    if (otherIdGenerator == null) {
      synchronized (lockObj) {
        if (otherIdGenerator == null) {
          otherIdGenerator = new DigitIdGenerator(server_id);
        }
      }
    }
    return otherIdGenerator;
  }

  /**
   * 主表生成方法
   *
   * @return long
   */
  public static long generateKey() {
    long id = getMainIdGenerator().next();
    return id;
  }

  /**
   * 其它表依赖于主键生成主键
   */
  public static long generateOtherKey(long mainId) {
    long id = getOtherIdGenerator().next(mainId);
    return id;
  }

  public static void main(String[] args) {
    System.out.println(generateKey());
  }

}
